package com.jijuxie.system.controller;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import com.jijuxie.common.core.R;
import com.jijuxie.common.exception.ServiceException;
import com.jijuxie.common.utils.CaptchaUtils;
import com.jijuxie.common.utils.SecurityUtils;
import com.jijuxie.system.domain.SysMenu;
import com.jijuxie.system.domain.SysUser;
import com.jijuxie.system.domain.dto.LoginDTO;
import com.jijuxie.system.service.ISysMenuService;
import com.jijuxie.system.service.ISysRoleService;
import com.jijuxie.system.service.ISysUserService;

import cn.dev33.satoken.stp.StpUtil;

/**
 * 系统登录控制器 处理用户登录、认证、会话等相关操作
 *
 * @author jijuxie
 */
@RestController
public class SysLoginController {

    private static final Logger log = LoggerFactory.getLogger(SysLoginController.class);

    @Autowired
    private ISysUserService userService;

    @Autowired
    private CaptchaUtils captchaUtils;

    @Autowired
    private ISysMenuService menuService;

    @Autowired
    private ISysRoleService roleService;

    /**
     * 获取验证码 生成图片验证码并缓存到Redis
     *
     * @return 验证码信息(包含uuid和base64图片)
     */
    @GetMapping("/captcha")
    public R<Map<String, Object>> getCaptcha() {
        return R.ok(captchaUtils.createCaptcha());
    }

    /**
     * 用户登录 1. 验证码校验 2. 用户名密码验证 3. 生成token
     *
     * @param loginDTO 登录参数(用户名、密码、验证码)
     * @return token和用户信息
     */
    @PostMapping("/auth/login")
    public R<Map<String, Object>> login(@RequestBody LoginDTO loginDTO) {
        log.info("用户登录请求: username={}", loginDTO.getUsername());

        // 验证码校验
        if (!captchaUtils.verifyCaptcha(loginDTO.getUuid(), loginDTO.getCode())) {
            throw new ServiceException("验证码错误");
        }

        // 用户验证
        SysUser user = userService.selectUserByUsername(loginDTO.getUsername());
        if (user == null) {
            throw new ServiceException("用户不存在");
        }
        if (!"0".equals(user.getStatus())) {
            throw new ServiceException("用户已停用");
        }

        // 密码验证
        if (!SecurityUtils.matchesPassword(loginDTO.getPassword(), user.getPassword())) {
            throw new ServiceException("密码错误");
        }

        // 生成token
        StpUtil.login(user.getUserId());

        // 获取角色列表并设置到 Sa-Token 中
        List<String> roleKeys = roleService.selectRolesByUserId(user.getUserId());
        log.info("用户角色列表: userId={}, roles={}", user.getUserId(), roleKeys);

        if (!roleKeys.isEmpty()) {
            StpUtil.getSession().set("roles", roleKeys);
            log.info("已设置用户角色到会话");
        }

        // 返回token和用户信息
        Map<String, Object> result = new HashMap<>();
        result.put("token", StpUtil.getTokenValue());
        result.put("user", user);

        return R.ok(result);
    }

    /**
     * 获取用户信息 包含用户基本信息、角色、权限菜单
     *
     * @return 用户完整信息
     */
    @GetMapping("/getInfo")
    public R<Map<String, Object>> getInfo() {
        // 获取当前登录用户
        SysUser user = userService.selectUserById(StpUtil.getLoginIdAsLong());

        Map<String, Object> result = new HashMap<>();
        result.put("user", user);
        // 获取角色和权限信息
        List<String> roleKeys = roleService.selectRolesByUserId(user.getUserId());
        List<SysMenu> menus = menuService.selectMenusByUserId(user.getUserId());
        result.put("roles", roleKeys);
        result.put("menus", menus);

        return R.ok(result);
    }

    /**
     * 退出登录 清除用户会话信息
     */
    @PostMapping("/logout")
    public R<Void> logout() {
        StpUtil.logout();
        return R.ok();
    }
}
